package com.example.fszq.volleydemo1;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;


import com.android.volley.NetworkResponse;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.example.fszq.volleydemo1.adapters.CataogryAdapter;
import com.example.fszq.volleydemo1.adapters.ImageSelectedAdapter;
import com.example.fszq.volleydemo1.utils.CatagoryList;
import com.example.fszq.volleydemo1.utils.MyUtil;
import com.example.fszq.volleydemo1.utils.Parsehtml;
import com.example.fszq.volleydemo1.utils.Requesttoserver;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class CatagoryActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.example.fszq.molleydemo1.MESSAGE";
    private static final int REQUEST_IMAGE = 2;
    private static final int REQUEST_LOGIN = 3;

    private List<CatagoryList> catList = new ArrayList<CatagoryList>();

    private Button shotButton,commitButton,loginButton,replyButton;
    private ListView listView;
    private GridView mGridView;

    private ImageSelectedAdapter sAdapter;
    private List<String> path,uPath;

    /*----网络访问相关 start--------*/
    private Requesttoserver Rserver = new Requesttoserver();
    private RequestQueue quence ;
    private Parsehtml Parse = new Parsehtml();


    /*---网络访问相关 end----------*/


    /*通用类*/
    private MyUtil myUtil = new MyUtil(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_catagory);

        //判断是否已经有历史目录信息，没有的话就获取并更新
        if(myUtil.getShared("catSource").length()==0) {
            updateCatagory();
        } else {
            String catSourceStr = myUtil.getShared("catSource");
            Gson gson = new Gson();
            List<CatagoryList> catListList = gson.fromJson(catSourceStr, new TypeToken<List<CatagoryList>>() {
            }.getType());
            showCatagory(catListList);
        }

        /*
        GetCatagory gCat = new GetCatagory();
        JSONArray returnJsonArray = gCat.getCat();
        Gson gson = new Gson();

        List<CatagoryList> catListList = gson.fromJson(returnJsonArray.toString(), new TypeToken<List<CatagoryList>>() {
        }.getType());
        for(CatagoryList t:catListList) {
            catList.add(t);
        }


        CataogryAdapter adapter = new CataogryAdapter(CatagoryActivity.this, R.layout.catagory_list, catList);
        listView = (ListView) findViewById(R.id.catagory_list);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                CatagoryList stopic = catList.get(position);
                Intent intent = new Intent(CatagoryActivity.this, MainActivity.class);
                Log.d("gettopicid", "vvv" + stopic.getCid());
                intent.putExtra(EXTRA_MESSAGE, stopic.getCid());
                startActivityForResult(intent, REQUEST_IMAGE);
            }
        });*/

    }


    //获取图片返回事件
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d("requestCode", requestCode+"");
        Log.d("resultCode",resultCode+"");

        if(requestCode == REQUEST_IMAGE){
            if(resultCode == RESULT_OK){
                // Get the result list of select image paths
                path = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);
                Log.d("result",path.size()+"");
                // do your logic ....

                //显示选择的图片
                mGridView = (GridView)findViewById(R.id.selected_view);
                sAdapter = new ImageSelectedAdapter(CatagoryActivity.this,R.layout.image_selected_grid_item,path);
                mGridView.setAdapter(sAdapter);
            }
        }
    }

    //判断share里面是否有原来目录记录，有的话就不处理，空的话则发一个http请求，获取返回结果
    private void updateCatagory() {
         JSONArray catListJsonArray;

        String url = "http://www.c2000.cn/index.asp";

        StringRequest stringRequest = new StringRequest(url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //把返回的内容写入进行解析并列出
                        JSONArray returnJsonArray = Parse.getCatJSON(response);
                        Gson gson = new Gson();

                        List<CatagoryList> catListList = gson.fromJson(returnJsonArray.toString(), new TypeToken<List<CatagoryList>>() {
                        }.getType());

                        //对list的内容进行排序
                        Collections.sort(catListList, new Comparator<CatagoryList>() {
                            @Override
                            public int compare(CatagoryList catagoryList, CatagoryList t1) {
                                int flag = catagoryList.getIdx() - t1.getIdx();
                                //Log.d("sortidx",flag+"");
                                return flag;
                            }
                        });

                        //保存share
                        //myUtil.saveShared("catSource",returnJsonArray.toString());
                        
                        //显示catagory
                        showCatagory(catListList);
                    }
                }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e("TAG", error.getMessage(), error);
            }


        }){
            @Override
            protected Response<String> parseNetworkResponse(NetworkResponse response) {
                String str = null;
                try {
                    str = new String(response.data, "gb2312");//这里写死不好哦
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return Response.success(str, HttpHeaderParser.parseCacheHeaders(response));
            }
        };

        quence.add(stringRequest);
    }

    private void showCatagory(List<CatagoryList> cL) {
        for(CatagoryList t:cL) {
            catList.add(t);
        }


        CataogryAdapter adapter = new CataogryAdapter(CatagoryActivity.this, R.layout.catagory_list, catList);
        listView = (ListView) findViewById(R.id.catagory_list);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                CatagoryList stopic = catList.get(position);
                Intent intent = new Intent(CatagoryActivity.this, MainActivity.class);
                Log.d("gettopicid", "vvv" + stopic.getCid());
                intent.putExtra(EXTRA_MESSAGE, stopic.getCid());
                startActivityForResult(intent, REQUEST_IMAGE);
            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_catagory, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
